/*
 * Copyright (C) 2015 yixun All Rights Reserved.
 * 
 * AreaServiceImpl.java
 */
package com.yixun.qfbao.api.service.impl;

import com.yixun.qfbao.api.service.CompanyService;
import com.yixun.qfbao.api.service.ResourcesService;
import com.yixun.qfbao.apidto.*;
import com.yixun.qfbao.constant.RedisKeyConstant;
import com.yixun.qfbao.mapper.ResourcesMapper;
import com.yixun.qfbao.model.Company;
import com.yixun.qfbao.model.PartnerInfo;
import com.yixun.qfbao.model.Resources;
import com.yixun.qfbao.model.dto.UserResourcesDto;
import com.yixun.qfbao.model.enums.PartnerInfoEnum;
import com.yixun.qfbao.model.enums.ResourcesOriginEnum;
import com.yixun.qfbao.model.enums.ResourcesTypeEnum;
import com.yixun.qfbao.service.PartnerInfoService;
import com.yixun.qfbao.util.RedisUtil;
import com.yixun.qfbao.xf.model.enums.ResultEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * [文件名称]<br>
 * LoginServiceImpl.java<br>
 * <br>
 * [文件描述]<br>
 * 登录、退出相关<br>
 * <br>
 * 
 * @author JHSong
 * @version 1.00
 */
@Service
public class ResourcesServiceImpl implements ResourcesService {
	
	private static Logger logger = LoggerFactory.getLogger(ResourcesServiceImpl.class);
	
	@Autowired
	private PartnerInfoService partnerInfoService;
	
	@Autowired
	private ResourcesMapper resourcesMapper;
	@Autowired
	private CompanyService companyService;
	
	
	@Override
	public GetMenuResDto getMenu(GetMenuReqDto getMenuReqDto) {
		GetMenuResDto resDto = new GetMenuResDto();
		PartnerInfo partnerInfo = partnerInfoService.selectById(Long.parseLong(getMenuReqDto.getUserId()));
		UserResourcesDto userResourcesDto = new UserResourcesDto();
		// 不是管理员
		if (partnerInfo.getAccountType().equals("1")) {
			userResourcesDto.setUserId(Long.parseLong(getMenuReqDto.getUserId()));
		}
		userResourcesDto.setResourcesOrigin(getMenuReqDto.getResourcesOrigin());
		userResourcesDto.setResourcesType(getMenuReqDto.getResourcesType());
		userResourcesDto.setResourcesLevel(getMenuReqDto.getResourcesLevel());
		userResourcesDto.setOrders("t2.resources_sort");
		List<Resources> responseList = findUserResources(userResourcesDto);
		if (responseList != null && responseList.size() > 0) {
			// 将对象处理成树
			ResourcesMapResDto resourcesMap = initResources(responseList, partnerInfo.getHigherid());
			resDto.setResourcesMap(resourcesMap);
			resDto.setResult(ResultEnum.SUCCESS.getNo());
			resDto.setResultMsg("菜单获取成功!");
		}
		return resDto;
	}

	/**
	 * 此方法目前只作用域案场助手,
	 * 若要用于其他系统,后续修改者请仔细甄别.
	 * @param getOptAuthReqDto
	 * @return
	 */
	@Override
	public GetOptAuthResDto getOptAuth(GetOptAuthReqDto getOptAuthReqDto) {
		GetOptAuthResDto resDto = new GetOptAuthResDto();
		List<String> list = new ArrayList<>();
		UserResourcesDto userResourcesDto = new UserResourcesDto();
		userResourcesDto.setResourcesType(ResourcesTypeEnum.APP.getNo());
		userResourcesDto.setResourcesOrigin(ResourcesOriginEnum.DEVELOPERS.getNo());
		// 管理员Key: 新增资源权限的时候,需要清除管理员的权限缓存.以便刷新新的进来
		String roleResourcesKey = RedisKeyConstant.RoleResources.RESOURCES_GETOPTAUTH_ROLEID_;
		//不是管理员
		if(PartnerInfoEnum.ACCOUNT_INDIVIDUAL.getCode().equals(getOptAuthReqDto.getAccountType())){
			roleResourcesKey = roleResourcesKey + getOptAuthReqDto.getRoleId();
			userResourcesDto.setUserId(Long.valueOf(getOptAuthReqDto.getUserId()));
		}
		Object object = RedisUtil.get(roleResourcesKey);
		if(Objects.nonNull(object)){
			list = (List<String>)object;
			resDto.setResult(ResultEnum.SUCCESS.getNo());
			resDto.setList(list);
			return resDto;
		}

		List<Resources> responseList;
		if(PartnerInfoEnum.ACCOUNT_MECHANISM.getCode().equals(getOptAuthReqDto.getAccountType())){
			responseList = findUserResources(userResourcesDto);
		}else{
			responseList = findUserResourcesNew(userResourcesDto);
		}
		for(Resources r :responseList){
			list.add(r.getResourcesCode());
		}
		RedisUtil.set(roleResourcesKey, list);
		resDto.setResult(ResultEnum.SUCCESS.getNo());
		resDto.setList(list);
		return resDto;
	}

	@Override
	public List<Resources> findUserResources(UserResourcesDto userResourcesDto) {
		return resourcesMapper.findUserResources(userResourcesDto);
	}
	
	private List<Resources> findUserResourcesNew(UserResourcesDto userResourcesDto) {
		return resourcesMapper.findUserResourcesNew(userResourcesDto);
	}

	/**
	 * 初始化资源
	 * 
	 * @param list
	 * @return
	 */
	public ResourcesMapResDto initResources(List<Resources> list, Long higherId) {
//		HashMap<String, List<Resources>> map = new HashMap<String, List<Resources>>();
		ResourcesMapResDto map = new ResourcesMapResDto();
		List<Resources> parent = new ArrayList<>();
		List<Resources> subNode = new ArrayList<>();
		if (list != null && list.size() > 0) {
			Company company = companyService.getCompanyById(higherId);
    		String outsideSwitch = company.getOutsideSwitch();
			for (Resources obj : list) {
				//无外部分销,过滤分销流量报表菜单
            	if("0".equals(outsideSwitch) || "".equals(outsideSwitch)) {
            		if("menu_0007_0004".equals(obj.getResourcesCode())) {
            			continue;
            		}
            	}
				Resources rrb = new Resources();
				BeanUtils.copyProperties(obj, rrb);
				if (obj.getParentCode().equals("menu_0000")) {
					parent.add(rrb);
				} else {
					subNode.add(rrb);
				}
			}
			map.setParent(parent);
			map.setSubNode(subNode);
		}
		return map;
	}

	@Override
	public GetUserAuthListResDto getUserAuthList(GetUserAuthListReqDto reqDto) {
		GetUserAuthListResDto resDto = new GetUserAuthListResDto();
		resDto.setResult(ResultEnum.FAIL.getNo());
		try{
			List<String> resourcesList = new ArrayList<String>();
			PartnerInfo pi = partnerInfoService.selectById(Long.valueOf(reqDto.getUserId()));
			
			UserResourcesDto userResourcesDto = new UserResourcesDto();
			//不是管理员
			if(pi.getAccountType().equals("1")){
				userResourcesDto.setUserId(pi.getId());
			}

			//查询类型 1:PC 2:移动端
			userResourcesDto.setResourcesType(reqDto.getResourcesType());
			//平台类型 1: 渠道商 2: 分销商
			userResourcesDto.setResourcesOrigin(reqDto.getResourcesOrigin());
			//资源类型 0: 菜单 1: 按钮
			userResourcesDto.setResourcesLevel(reqDto.getResourcesLevel());
			List<Resources> responseList = findUserResources(userResourcesDto);
			for(Resources r : responseList){
				resourcesList.add(r.getResourcesCode());
			}
			resDto.setResult(ResultEnum.SUCCESS.getNo());
			resDto.setResourcesList(resourcesList);
		}catch (Exception e){
			logger.error("功能资源获取失败: {}", e);
			resDto.setResultMsg("功能资源获取失败: " + e.getMessage());
		}
		return resDto;
	}

}
